<?php
namespace app\cloud\controller;
use function GuzzleHttp\default_user_agent;
use think\Controller;
use think\Db;
use think\Cache;
use think\View;
use think\Request;
use mlsmt\Cabinet\Send;
//用于接收相关数据，
class Reception extends Controller
{
    public function _initialize()
    {

        $key = config('headerkey');
        $requestkey = Request::instance()->header('key');
        $time = Request::instance()->header('time');
        $key = md5($key.$time);

        $difference = time() - (int)$time;
        if($requestkey != $key||($difference&&$difference>180)||($difference&&$difference<-180)){
            $data = array(
                'mykey' => $key,
                'mytime' =>time(),
                'requestkey' => $requestkey,
                'requesttime' => $time,
            );
            die('非法请求！');
        }
    }

    //结束订单
    private function endleaseorder($batteryid){

        //处理归还订单
        $leaseorder = Db::name('leaseorder')
            ->where('deviceid',$batteryid)
            ->where('status',1)
            ->find();
        if(!$leaseorder){
            return '无法找到该租借订单';
        }

        $oid = $leaseorder['oid'];
        $uid = $leaseorder['uid'];
        $orderid = $leaseorder['id'];

        //获取运营商价格
        $operator = Db::name('operator')
            ->where('id',$oid)
            ->find();

        if ($operator['billingunit'] == 1) {

            $arithmetical = 3600;  //计算基数
        } else {
            $arithmetical = 60;//计算基数
        }
        $time = time(); //当前时间
        $leasetime = $time - $leaseorder['starttime'];
        //判断是否启用免费时长
        if($operator['freetime']!=0){
            //计算收费时长
            $billingtime =  $leasetime - ($operator['freetime']*60);
        }else{
            $billingtime = $leasetime;
        }
        //如果收费时长大于0，计算价格，否则价格为免费
        if($billingtime>0){
            $onedayamount = (86400/($arithmetical * $operator['billingtime'])) * $operator['amount']; //按标准价格一整天的金额

            if( $operator['ceiling']>0 && $onedayamount>$operator['ceiling']) {//一整天的标准价 > 设置的封顶价
                //除去整天，剩余的计费时长
                $billingseconds = $billingtime % 86400;
                $billingunit = ceil($billingseconds / ($arithmetical * $operator['billingtime']));
                $amountseconds = $billingunit * $operator['amount'];
                if($amountseconds > $operator['ceiling']) {
                    $amountseconds = $operator['ceiling'];
                }
                //计费天数
                $dayamount = (($billingtime - $billingseconds) / 86400) * $operator['ceiling'];//按每天封顶金额计算的价格
                $amount = $dayamount + $amountseconds;
            }else{//一整天的标准价 <= 设置的封顶价
                $billingunit = ceil($billingtime / ($arithmetical * $operator['billingtime']));
                $amount = $billingunit * $operator['amount'];
            }
        }else{
            $billingunit = 0;
            $amount = 0;
        }

        $data = array(
            'endtime' => $time,
            'billingunit' => $billingunit,
            'amount' => $amount,
            'status' => 2,
            'payable_amount' => $amount,
            'real_amount' => $amount,
        );
        Db::name('leaseorder')->where('oid',$oid)->where('id',$orderid)->update($data);
        Db::name('user')->where('oid',$oid)->where('id',$uid)->setDec('balance', $amount);

        if(isset($leaseorder['formid'])){
            $user = Db::name('user')
                ->where('id',$uid)
                ->field('openid')
                ->find();

            //租借时长（转换为分钟或小时）
            $duration = ceil(($leasetime)/$arithmetical);
            if ($operator['billingunit'] == 1) {
                $duration .= '小时';

            } else {
                $duration .= '分钟';
            }

            //发送归还成功通知
            $id = array(
                'oid' => $oid,
                'formid' => $leaseorder['formid'],
                'orderid' => $orderid,
                'opneid' => $user['openid'],
            );

            $template = array(
                'order_no' => $leaseorder['order_no'],
                'starttime' => $leaseorder['starttime'],
                'endtime' => $data['endtime'],
                'duration' => $duration,
                'real_amount' => $data['real_amount'],
            );
            //save_log('../log/equipment',111);
            /*$Openplatform  = controller('Openplatform');
            $res =  $Openplatform->sendtemplate($id,$template);
            //save_log('123');
            if($res) {
                return true;
            }else{
                return false;
            }*///template_id 暂无，先不走此处
            return true;
        }
    }

    //登陆信息

    /**
     * @return int 0 登陆失败
     * 1 登陆成功； 2 失败，时间错误
     */
    public function Login()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $clientip = Request::instance()->post('clientip'); //客户端IP地址
            $client_id = Request::instance()->post('client_id'); //连接ID
            $hex = Request::instance()->post('hex'); //十六进制信息
            $cabinet = Db::name('charecabinet')->where(['cabinet_id'=>$cabinet_id, 'is_delete'=>1])->find();

            if ($cabinet) {
                $data['registertime'] = time();
                $data['clientip'] = $clientip;
                $data['client_id'] = $client_id;
                //将登陆信息写入缓存
                Cache::store('redis')->set($cabinet_id, $data);
                Cache::store('redis')->set($client_id, $cabinet_id);
                return 1;
            } else {
                return 2;//登陆失败
            }

        }else{
            return 3;
        }

    }
    //注销登陆
    public function logout()
    {
        if ( Request::instance()->isPost() ) {
            $client_id = Request::instance()->post('client_id'); //连接ID
            $cabinet_id = Cache::store('redis')->get($client_id);

            if($cabinet_id){
                $cabinet = Cache::store('redis')->get($cabinet_id);

                if($cabinet['client_id']==$client_id){

                    //删除相关在线信息
                    Cache::store('redis')->rm($cabinet_id);
                    Cache::store('redis')->rm($client_id);
                }else{
                    Cache::store('redis')->rm($client_id);

                }
            }else{
                Cache::store('redis')->rm($client_id);
            }


        }

    }

    //心跳
    public function HeartBeat()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $hex = Request::instance()->post('hex'); //十六进制信息
            $cabinet = Cache::store('redis')->get($cabinet_id);
            if($cabinet){
                $cabinet['heartbeattime'] = time();
                Cache::store('redis')->set($cabinet_id,$cabinet);
            }else{
                $clientip = Request::instance()->post('clientip'); //客户端IP地址
                $client_id = Request::instance()->post('client_id'); //连接ID
                $data['heartbeattime'] = time();
                $data['registertime'] = time();
                $data['clientip'] = $clientip;
                $data['client_id'] = $client_id;
                Cache::store('redis')->set($cabinet_id,$data);
            }
        }
    }
    //判断是否在线(建议使用查询库存数量来判断,有可能客户端掉线后，并未及时关闭连接，导致查询结果错误！)
    public function isOnline(){
        $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
        $isonline = Request::instance()->post('isonline'); //是否在线

        if(!$isonline){
            //删除相关在线信息
            Cache::store('redis')->rm($cabinet_id);
        }
    }
    //库存数量
    /*public function StockNum()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $stocknum = Request::instance()->post('stocknum'); //库存数量
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);
            $cabinet['stocknum'] = $stocknum;
            $cabinet['stocknumhex'] = $hex;
            Cache::store('redis')->set($cabinet_id,$cabinet);
        }
    }*/

    //机柜能容纳的充电宝个数
    public function LockNum()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $devicenum = Db::name('charecabinet')->where(['cabinet_id' => $cabinet_id, 'is_delete' => 1])->field('cabinet_id, devicenum')->find();
            return $devicenum['devicenum'];
        }
    }

    //库存明细
    public function StockDetail()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $detail = Request::instance()->post('detail'); //明细
            $devicenum = Request::instance()->post('stocknum'); //库存数量
            $hex = Request::instance()->post('hex'); //十六进制信息

            $detail = json_decode($detail);//object
            $cabinet = Cache::store('redis')->get($cabinet_id);
            $cabinet['detailhex'] = $hex;
            $cabinet['detailstatus'] = 1;
            $detail = json_encode($detail);
            $detail = json_decode($detail,true);//array
            $cabinet['detail'] = $detail;
            $powernu = 0 ;  //可借的充电宝数量
            if($detail){
                foreach ($detail as $key => $value) {
                    $leaseorder = Db::name('leaseorder')
                        ->where('deviceid',$value['batteryid'])
                        ->where('status',1)
                        ->find();
                    if($leaseorder){
                        $this -> endleaseorder($value['batteryid']);
                    }
                    if($value['power']>=3){//电量80%
                        $powernu++;
                    }
                }
            }
            $cabinet['powernu'] = $powernu;
            $cabinet['stocknum'] = $devicenum;

            Cache::store('redis')->set($cabinet_id,$cabinet);
        }

    }
    //查询充电宝ID
    public function Batteryid()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $lockid = Request::instance()->post('lockid'); //锁ID
            $batteryid = Request::instance()->post('batteryid'); //充电宝ID
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);

            $cabinet['detail'][$lockid] = array(
                'batteryid' => $batteryid,
                'batteryidhex' => $hex,
            );

            Cache::store('redis')->set($cabinet_id,$cabinet);
        }

    }
    //借出充电宝返回状态
    public function BorrowDevice()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $lockid = Request::instance()->post('lockid'); //锁ID
            $finally = Request::instance()->post('finally'); //状态
            $batteryid = Request::instance()->post('batteryid'); //充电宝ID
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);

            if($finally){//如果借出成功

                $cabinet['status'][$lockid] = array(
                    'batteryid' => $batteryid,
                    'borrowhex' => $hex,
                    'borrowstatus' => 1,
                );
                if(isset($cabinet['stocknum']) && isset($cabinet['powernu'])){
                    if($cabinet['stocknum']>0){
                        $cabinet['stocknum']--;
                        $cabinet['powernu']--;
                    }
                }else{
                    //更新当前明细到缓存
                    $Send = new Send($cabinet_id);
                    $str = "111,".$cabinet_id;
                    $Send ->socket($str);
                }

            }else{
                if(isset($cabinet['buglock'])){
                    $cabinet['buglock'] .= ','.$lockid;
                }else{
                    $cabinet['buglock'] = $lockid;
                }

                $cabinet['status'][$lockid] = array(
                    'borrowstatus' => 2,
                );

            }

            Cache::store('redis')->set($cabinet_id,$cabinet);

        }
    }

    //还回充电宝
    //0归还失败；1归还成功；4非法充电宝ID；
    public function ReturnBattery()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $lockid = Request::instance()->post('lockid'); //锁ID
            $batteryid = Request::instance()->post('batteryid'); //充电宝ID

            //查询数据库充电宝记录表，判断是否有该id记录
            $is_batteryid = Db::name('portablebattery')
                ->where('device_id',$batteryid)
                ->where('is_delete',1)
                ->find();
            //查询充电宝的oid与机柜oid是否一致
            $is_match = Db::name('charecabinet')
                ->where('cabinet_id', $cabinet_id)
                ->where('is_delete', 1)
                ->field('oid')
                ->find();

            if (!$is_batteryid || $is_batteryid['oid'] !== $is_match['oid']) {
                return 4;
            }
            $cabinet = Cache::store('redis')->get($cabinet_id);

            $cabinet['status'][$lockid] = array(
                'batteryid' => $batteryid,
                'returntime' => time(),
            );

            $devicenum = Db::name('charecabinet')->where(['cabinet_id' => $cabinet_id, 'is_delete' => 1])->field('cabinet_id, devicenum')->find();

            if (isset($cabinet['stocknum']) && isset($cabinet['powernu'])) {
                if ($cabinet['stocknum'] < $devicenum) {
                    $cabinet['stocknum']++;
                    $cabinet['powernu']++;
                }
            }
            Cache::store('redis')->set($cabinet_id,$cabinet);
            //结束订单
            $this -> endleaseorder($batteryid);
            return 1;
        }else{
            return false;
        }
    }
    //查询版本
    public function Version()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $version = Request::instance()->post('version'); //版本
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);
            $cabinet['version'] = $version;
            $cabinet['versionhex'] = $hex;
            $cabinet = Cache::store('redis')->set($cabinet_id,$cabinet);

        }
    }



    //返回查询配置文件状态
    public function GetConfigure()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $addr = Request::instance()->post('addr'); //服务器地址
            $port = Request::instance()->post('port'); //端口
            $heartbeat = Request::instance()->post('heartbeat'); //心跳间隔
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);

            $cabinet['servicer'] = $addr;
            $cabinet['port'] = $port;
            $cabinet['heartbeat'] = $heartbeat;
            $cabinet['configurehex'] = $hex;

            $cabinet = Cache::store('redis')->set($cabinet_id,$cabinet);


        }

    }


    //返回更新配置文件状态
    public function UpdateStatus()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $status = Request::instance()->post('status'); //更新状态
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);
            if($status){
                $cabinet['updatestatus'] = $status;
                $cabinet['updatehex'] = $hex;
                $cabinet = Cache::store('redis')->set($cabinet_id,$cabinet);
            }


        }

    }

    //返回远程升级状态
    public function RemoteUpdate()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $status = Request::instance()->post('status'); //更新状态
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);
            if($status){
                $cabinet['otatatus'] = $status;
                $cabinet['otahex'] = $hex;
                $cabinet = Cache::store('redis')->set($cabinet_id,$cabinet);
            }


        }

    }

    //返回重启状态
    public function Restart()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $status = Request::instance()->post('status'); //更新状态
            $hex = Request::instance()->post('hex'); //十六进制信息

            $cabinet = Cache::store('redis')->get($cabinet_id);
            if($status){
                $cabinet['restartstatus'] = $status;
                $cabinet['restarthex'] = $hex;
                $cabinet = Cache::store('redis')->set($cabinet_id,$cabinet);
            }


        }

    }


    //上报电量
    /*public function UpdatePower()
    {
        if ( Request::instance()->isPost() ) {
            $cabinet_id = Request::instance()->post('cabinet_id'); //机柜ID
            $lockid = Request::instance()->post('lockid'); //锁ID
            $batteryid = Request::instance()->post('batteryid'); //充电宝ID
            $power = Request::instance()->post('power'); //电量
            $hex = Request::instance()->post('hex'); //十六进制信息


            $Send = new Send($cabinet_id);
            $logdata = array(
                'oid' => $oid,
                'mode' => 1,
                'operation' => 12,
                'info' => $batteryid,
                'resstatus'=> 1,
                'result' => array($lockid=> array('batteryid' =>$batteryid ,'power'=>$power )),
                'reshex' => $hex,
                'create_user' => 0,
            );
            $Send->Log($logdata);//记录机柜日志

            $cabinet = Cache::store('redis')->get($cabinet_id);

            $cabinet['detail'][$lockid] = array(
                'batteryid' => $batteryid,
                'power'=> $power,
            );
            $detail = $cabinet['detail'];
            $detail = json_encode($detail);
            $detail = json_decode($detail,true);
            $powernu = 0 ;  //可借的充电宝数量
            if($detail){
                foreach ($detail as $key => $value) {
                    $leaseorder = Db::name('leaseorder')
                        ->where('deviceid',$value['batteryid'])
                        ->where('status',1)
                        ->find();
                    if($leaseorder){
                        $this -> endleaseorder($value['batteryid']);
                    }
                    if($value['power']>=3){//80%电量
                        $powernu++;
                    }
                }
            }
            $cabinet['powernu'] = $powernu;
            Cache::store('redis')->set($cabinet_id,$cabinet);

        }

    }*/
}

